import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/msg/model/alarm_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';

class MsgPage extends ConsumerStatefulWidget {
  const MsgPage({super.key});

  @override
  ConsumerState<MsgPage> createState() => _MsgPageState();
}

class _MsgPageState extends ConsumerState<MsgPage> with AutomaticKeepAliveClientMixin {
  late EasyRefreshController _refreshController;

  List<AlarmData> _alarmList = <AlarmData>[];
  int _total = 0;
  int _pageNum = 1;
  bool showLoading = true;

  /// 保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _fetchAlarmList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  Future _fetchAlarmList(bool isRefresh) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.expired == true) {
      setState(() {
        showLoading = false;
        _pageNum = 1;
        _alarmList = <AlarmData>[];
      });
      _refreshController.finishRefresh();
      return;
    }
    final postData = {
      'deviceId': deviceInfo.imei,
      'pageNum': _pageNum,
    };
    final res =
        await post<AlarmListResp, AlarmListResp>('/deviceAlarm/list', data: postData, decodeType: AlarmListResp());
    setState(() {
      showLoading = false;
    });
    res.when(success: (resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          _alarmList = resp.rows!;
          _total = resp.total!;
          _refreshController.finishRefresh();
          _pageNum++;
        } else {
          // 判断是否还有数据
          if (resp.rows!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
            return;
          } else {
            _pageNum++;
            _alarmList.addAll(resp.rows!);
            _refreshController.finishLoad();
          }
        }
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取告警列表失败 code: $code msg: $msg');
    });
  }

  _showLoading() {
    if (showLoading) {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    } else {
      return _buildListView();
    }
  }

  _listBuilder() {
    return ListView.separated(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        itemCount: _alarmList.length,
        separatorBuilder: (context, index) => const SizedBox(height: 12),
        itemBuilder: (context, index) {
          AlarmData alarmData = _alarmList[index];
          // 时间格式化
          final dateStr = DateUtil.formatDate(alarmData.occurTime!, format: 'yyyy-MM-dd');
          final timeStr = DateUtil.formatDate(alarmData.occurTime!, format: 'HH:mm:ss');

          return _MsgTile(
            title: alarmData.warnDesc ?? '',
            subtitle: '${alarmData.deviceName}(${alarmData.deviceId})',
            date: dateStr,
            time: timeStr,
          );
        });
  }

  _buildListView() {
    return EasyRefresh(
        controller: _refreshController,
        onRefresh: () async {
          _pageNum = 1;
          _fetchAlarmList(true);
        },
        onLoad: () async {
          _fetchAlarmList(false);
        },
        child: Stack(
          children: [
            _listBuilder(),
            Offstage(
              offstage: _alarmList.isNotEmpty,
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  '暂无告警消息',
                  style: TextStyle(
                    fontSize: 16,
                    color: AppTheme.themeConfig.infoTextColor,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "消息",
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: Colors.grey.shade100,
      body: _showLoading(),
    );
  }
}

class _MsgTile extends StatelessWidget {
  final String title;
  final String subtitle;
  final String date;
  final String time;
  const _MsgTile({required this.title, required this.subtitle, required this.date, required this.time});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Colors.orange.shade400.withOpacity(0.15),
                      Colors.orange.shade600.withOpacity(0.05),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(
                  Icons.notifications_active,
                  color: Colors.orange.shade600,
                  size: 20,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    color: AppTheme.themeConfig.primaryTextColor,
                    height: 1.3,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          // 分割线
          Container(
            height: 1,
            color: AppTheme.themeConfig.dividerColor,
          ),
          const SizedBox(height: 12),
          // 设备信息行
          Row(
            children: [
              Icon(
                Icons.phone_android,
                color: AppTheme.themeConfig.infoTextColor,
                size: 16,
              ),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  subtitle,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: AppTheme.themeConfig.secondaryTextColor,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          // 时间行
          Row(
            children: [
              Icon(
                Icons.access_time,
                color: AppTheme.themeConfig.primaryColor,
                size: 16,
              ),
              const SizedBox(width: 6),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  '$date  $time',
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
